package com.walle.ak47.commons.jaxrs.cxf.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cxf.Bus;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.message.Message;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import com.walle.ak47.commons.jaxrs.BizExceptionMapper;
import com.walle.ak47.commons.jaxrs.ServerExceptionMapper;
import com.walle.ak47.commons.jaxrs.cxf.interceptor.CheckHeader;
import com.walle.ak47.commons.jaxrs.cxf.log.Log4jLoggingInInterceptor;
import com.walle.ak47.commons.jaxrs.cxf.log.Log4jLoggingOutInterceptor;
import com.walle.ak47.commons.utils.SpringContextHolder;

/**
 * // FIXME 待完成，不影响功能
 * 
 * @author admin 待补充
 * 
 */
public class SimpleJarxServer {

	public SimpleJarxServer(String address, Object servcieBean, boolean isPintLog) {
		
		JAXRSServerFactoryBean jaxrsServer = new JAXRSServerFactoryBean();
		
		List<Interceptor<? extends Message>> inInterceptors = new ArrayList<Interceptor<? extends Message>>();
		List<Interceptor<? extends Message>> outInterceptors = new ArrayList<Interceptor<? extends Message>>();
		
		inInterceptors.add(new CheckHeader() );
		
		if(isPintLog)
		{
			inInterceptors.add(new Log4jLoggingInInterceptor());
			outInterceptors.add(new Log4jLoggingOutInterceptor());
		}
		
		Map<Object, Object> extensionMappings = new HashMap<Object, Object>();
		extensionMappings.put("json", "application/json");
		extensionMappings.put("xml", "application/xml");

		List<Object> providers = new ArrayList<Object>();
		JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
		jacksonJsonProvider.setMapper(new com.walle.ak47.commons.jaxrs.JaxrsJson());
		providers.add(jacksonJsonProvider);
		providers.add(new BizExceptionMapper());
		providers.add(new ServerExceptionMapper());
		
		jaxrsServer.setInInterceptors(inInterceptors);
		jaxrsServer.setOutInterceptors(outInterceptors);
		jaxrsServer.setExtensionMappings(extensionMappings);
		jaxrsServer.setProviders(providers);
		
		jaxrsServer.setBus((Bus) SpringContextHolder.getBean("cxf"));
		jaxrsServer.setAddress(address);
		jaxrsServer.setServiceBean(servcieBean);

		jaxrsServer.create();
	}

}
